package myTimer;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: tao
 * Date: 2023-12-05
 * Time: 16:16
 */
class MyTimer2Task implements Comparable<MyTimer2Task>{
    //要执行的代码
    private Runnable runnable;
    //预期啥时候执行代码的时间
    private long time;
    public long getTime() {
        return this.time;
    }
    @Override
    public int compareTo(MyTimer2Task o) {
        return (int)(this.time - o.time);
    }
    public void run() {
        runnable.run();
    }
    public MyTimer2Task(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }
}
class MyTimer2 {
    Object locker = new Object();
    //负责扫描的线程
    private Thread t;
    //任务队列
    private PriorityQueue<MyTimer2Task> queue = new PriorityQueue<>();
    //入队列的方法
    public void schedule(Runnable runnable, long time) {
        synchronized (locker) {
            MyTimer2Task task = new MyTimer2Task(runnable, time);
            queue.offer(task);
            locker.notify();
        }
    }
    //构造方法，创建线程，让这个线程去判断和执行
    public MyTimer2() {
        Thread t = null;
        t = new Thread(() -> {
            while (true) {
                try {
                    synchronized (locker) {
                        while (queue.isEmpty()) {
                            //阻塞等待
                            locker.wait();
                        }
                        MyTimer2Task task = queue.peek();
                        //判断是否到时间了，到时间就执行要执行的代码，并且出队列；没到时间就等待
                        long curTime = System.currentTimeMillis();
                        if(curTime >= task.getTime()) {
                            //到时间了
                            MyTimer2Task tmp = queue.poll();
                            tmp.run();
                        } else {
                            //等待规定的时间
                            locker.wait(task.getTime() - curTime);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
        t.start();
    }
}
public class TimerTest2 {
    public static void main(String[] args) {
        MyTimer2 timer = new MyTimer2();
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 3000");
            }
        }, 3000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 2000");
            }
        }, 2000);
        timer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("hello 1000");
            }
        }, 1000);
        System.out.println("hello main");
    }
}
